package compiler.ast;

import java.io.PrintStream;
import java.util.ArrayList;

import compiler.tac.BasicBlock;
import compiler.tac.ExitBlock;
import compiler.tac.ThreeAddressCode;

public class FunctionCall extends Statement implements Factor{
	Identifier functionName;
	ArrayList<Expression> parameters;
	
	public FunctionCall(Identifier name) {
		this.functionName = name;
		this.parameters = new ArrayList<Expression>();
	}
	
	public void addParam(Expression param) {
		parameters.add(param);
	}

	public void printDotFormat(PrintStream out, String node) {
		out.println(node +"[label=\"{call|"+functionName.name()+"}\"];");

		int order = 0;
		for (Expression expr : parameters) {
			out.println(node+"->"+node+order+";");
			expr.printDotFormat(out, node+order);
			order++;
		}
	}

	@Override
	public BasicBlock toThreeAddressCode(ThreeAddressCode tac, BasicBlock prev,
			ExitBlock exit) {
		if(parameters.size() > 0)
			for(int i = 0; i < parameters.size(); i ++)
			{
				String temp = parameters.get(i).toThreeAddressCode(tac, prev);
				prev.addParamInstruction(temp);
			}
		prev.addCallInstruction(this.functionName.name());
		return prev;
	}

	@Override
	public String toThreeAddressCode(ThreeAddressCode tac, BasicBlock prev) {
		if(parameters.size() > 0)
			for(int i = 0; i < parameters.size(); i ++)
			{
				String temp = parameters.get(i).toThreeAddressCode(tac, prev);
				prev.addParamInstruction(temp);
			}
		prev.addCallInstruction(this.functionName.name());

		return ThreeAddressCode.returnTemp;
	}
}
